package cn.xiaopengstack.domain.agent.service.armory.node;

import cn.bugstack.wrench.design.framework.tree.StrategyHandler;
import cn.xiaopengstack.domain.agent.model.entity.ArmoryCommandEntity;
import cn.xiaopengstack.domain.agent.model.valobj.AiAgentEnumVO;
import cn.xiaopengstack.domain.agent.model.valobj.AiClientAdvisorTypeEnumVO;
import cn.xiaopengstack.domain.agent.model.valobj.AiClientAdvisorVO;
import cn.xiaopengstack.domain.agent.service.armory.AbstractArmorySupport;
import cn.xiaopengstack.domain.agent.service.armory.factory.DefaultArmoryStrategyFactory;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jiangyangang
 */
@Service
@Slf4j
public class AiClientAdvisorNode extends AbstractArmorySupport {
    @Resource
    private VectorStore vectorStore;

    @Resource
    private AiClientNode aiClientNode;

    @Override
    protected String beanName(String id) {
        return AiAgentEnumVO.AI_CLIENT_ADVISOR.getBeanName(id);
    }

    @Override
    protected String dataName() {
        return AiAgentEnumVO.AI_CLIENT_ADVISOR.getDataName();
    }

    @Override
    protected String doApply(ArmoryCommandEntity requestParameter, DefaultArmoryStrategyFactory.DynamicContext dynamicContext) throws Exception {
        List<AiClientAdvisorVO> advisorVOList = dynamicContext.getValue(dataName());
        if (CollectionUtils.isEmpty(advisorVOList)) {
            log.info("AI客户端加载，无可加载的AI Advisor...");
            return router(requestParameter, dynamicContext);
        }

        log.info("AI客户端加载，AI Advisor【{}】", JSONObject.toJSONString(advisorVOList.stream().map(advisorVO -> {return  advisorVO.getAdvisorId() + "_" + advisorVO.getAdvisorName();}).collect(Collectors.joining(","))));
        // 组装所有的顾问对象
        for (AiClientAdvisorVO advisorVO : advisorVOList){
            String advisorType = advisorVO.getAdvisorType();
            AiClientAdvisorTypeEnumVO advisorTypeEnumVO = AiClientAdvisorTypeEnumVO.getByType(advisorType);
            Advisor advisor = advisorTypeEnumVO.createAdvisor(advisorVO, vectorStore);
            registerBean(beanName(advisorVO.getAdvisorId()), Advisor.class, advisor);
        }

        return router(requestParameter, dynamicContext);
    }

    @Override
    public StrategyHandler<ArmoryCommandEntity, DefaultArmoryStrategyFactory.DynamicContext, String> get(ArmoryCommandEntity requestParameter, DefaultArmoryStrategyFactory.DynamicContext dynamicContext) throws Exception {
        return aiClientNode;
    }
}
